package com.alibaba.dubbo.common.inet;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

/**
 * inet地址辅助工具
 * 
 * @author kingbo.ruan 2014.09.24
 */
public class InetAddressSupport {
	public static long ipToLong(InetAddress ip) {
		byte[] octets = ip.getAddress();
		return ipToLong(octets);
	}

	public static long ipToLong(byte[] ip) {
		long result = 0;
		for (byte octet : ip) {
			result <<= 8;
			result |= octet & 0xff;
		}
		return result;
	}

	public static long ipToLong(int[] ip) {
		long result = 0;
		for (int octet : ip) {
			result <<= 8;
			result |= octet & 0xff;
		}
		return result;
	}

	public static long ipToLong(String ip) {
		String[] parts = ip.trim().split("\\.");
		if (parts.length > 4) {
			throw new IPMatcherException("Malformed IP specification " + ip);
		}

		int[] sparts = new int[4];
		try {
			for (int i = 0; i < parts.length; i++) {
				String part = parts[i];
				int p = Integer.parseInt(part);
				if (p < 0 || p > 255) {
					throw new IPMatcherException("Malformed IP specification "
							+ ip);
				}
				sparts[i] = p;
			}
		} catch (NumberFormatException nfe) {
			throw new IPMatcherException("Malformed IP specification " + ip,
					nfe);
		}
		return ipToLong(sparts);
	}
	
	public static byte[] ipv4ToBytes(String ip){
		String []parts = ip.split("\\."); 
		byte []bytes = new byte[4];
		for (int i = 0; i < parts.length; i++) {
			String part = parts[i];
			int p = Integer.parseInt(part);
			if (p < 0 || p > 255) {
				throw new IPMatcherException("Malformed IP specification " + ip);
			}
			bytes[i] = (byte)(p > 128 ? p -256:p);
		}
		return bytes;
	}
	
	
	public static InetAddress ipv4ToInetAddress(String ip) throws UnknownHostException{
		return InetAddress.getByAddress(ipv4ToBytes(ip));
	}
}
